/* typehints:start */
import { Application } from "../application";
/* typehints:end */

import { createLogger } from "./utils/logging";

const logger = createLogger('api')

export class Api{
  constructor(app){
    /** @type {Application} */
    this.app = app;
  }

  getUrl(){
    if(G_IS_DEV){
      return 'http://localhost:3555';
    } 
    return 'http://game.lionet.cloud:3555';
  }

  _request(url, options = {}){
    return Promise.race([
      fetch(this.getUrl() + url, {
        cache: 'no-cache',
        mode: 'cors',
        method: options.method || 'GET',
        body: options.body ? JSON.stringify(options.body) : undefined
      })
      .then(res => {
        if(res.status !== 200){
          throw 'bas-status: ' + res.status + ' / ' + res.statusText;
        }
        return res;
      })
      .then(res => res.json()),
      // 如果服务器无响应，加载会卡在请求版。
      new Promise((resolve, reject) => setTimeout(() => reject('timeout'), 5000))
    ])
    .then(data => {
      if(data && data.error){
        logger.warn('服务器api错误: ', data);
        throw data.error;
      }
      return data;
    })
    .catch(err => {
      logger.warn('错误：', url, ':', err);
      throw err;
    })
  }

  getVersion(){
    return this._request('/version')
  }

  getWgt(){
    return this._request('/wgt')
  }

  saveMap(version, data){
    return this._request('/map/save', {
      method: 'post',
      body: {
        mapData: data,
        version
      }
    })
  }
}